//try_coin:当前结算的总试豆,ship_amount_try_coin:邮费抵扣用的试豆,order_amount:订单金额,ship_amount:原始邮费,ship_amount_discount:优惠后的邮费
var cellReg = /^1[34578]{1}\d{9}$/;//手机号
var cellCodeReg = /^[0-9]{6}$/;//短信验证码
$(function () {
	//返回
	$("#back").on("click", function(){
		$.go(backUrl)
	});
	//地址选择
	$("#addressSelect").on("click", function(){
		$.go(addressListUrl);
	});
	//喜元抵扣
	$("#orderDeduct").on("click", function(){
		var error = $(this).siblings(".error");
		var _this = this;
		if(orderData.member_address_id*1==0){
			$.tips("请选择地址");
			return false;
		}else if ($(this).is(".selected")) {
			error.text('');
			orderData.use_coin_for_ship_amount = 0;
            $("#settleExpressCharge").text("￥"+userInfo.expressCharge);
            $("#settleAmount").text(userInfo.settleAmount);
            $("#settleSD").text(userInfo.try_coin);
			$(_this).removeClass("selected");
        } else {
			if(!userInfo.validate){
				delete orderData.member_money;
			}
			orderData.use_coin_for_ship_amount = 1;
			$.loader("请稍候...");
			$.doAjax({
				url: sdDeductUrl,
				type: "post",
				data: orderData,
				success: function (data) {
					$.loaded();
					if(!data.flag){
						orderData.use_coin_for_ship_amount = 0;
						var coinMsg = data.msg.ship_amount_try_coin;//试豆抵扣邮费错误字段名为ship_amount_try_coin
						if(coinMsg){
							$.tips(coinMsg[0]);
							return false;
						}else{
							$("#settleExpressCharge").text(data.ship_amount_try_coin+"试豆");
							$("#settleAmount").text(data.order_amount);
							$("#settleSD").text(data.try_coin);
							$(_this).addClass("selected");
						}
						
					}else{
						error.text('');
						$("#settleExpressCharge").text(data.ship_amount_try_coin+"试豆");
						$("#settleAmount").text(data.order_amount);
						$("#settleSD").text(data.try_coin);
						$(_this).addClass("selected");
					}
					
				}
			});
        }
	});
	//打开余额支付
	$("#payByBalance").on("click", function () {
		$(this).find(".icon").toggleClass("up");
		$(this).next().toggle();
	});
	//余额支付-输入
	$("#orderPayBalance").on("input", function(){
		var error = $("#balanceError");
		var balanceInput = $(this).val()*1;
		if(balanceInput>userInfo.balance*1){
			error.text("您的余额不足请重新输入");
		}else if(isNaN(balanceInput)){
			error.text("非法金额");
		}else{
			error.text("");
		}
	});
	//余额支付-确认
	$("#orderPayConfirm").on("click", function(){
		var error = $("#balanceError");
		var balanceInput = $("#orderPayBalance").val();
		var _this = this;
		if(balanceInput==""){
			error.text("请输入金额");
		}else if(!error.text()){
			if(userInfo.isBind&&!userInfo.validate){
				orderData.member_money = balanceInput;
				$.confirm(["安全提示", validateHtml3, "取消", "确定"], false, function(box){
					var cellCode = $("#cellCode").val();
					var error = $("#validateError");
					if(!cellCode.match(cellCodeReg)){
						error.text("验证码有误请重新输入！");
					}else{
						error.text('');
						orderData.smsConfirm = cellCode;
						processAjax(checkCellCodeForBalancePayUrl, orderData, function(data){
							if(!data.flag)return false;
							userInfo.settleAmount = data.order_amount;
							userInfo.validate = true;
							$("#orderPayBalance").prop("disabled", true);
							$(_this).addClass("dis").off();
							updateSettleInfo(data);
							$.tips("手机验证成功");
							box.hide();
						});
					}
					return false;
				});
			}else if(!userInfo.isBind&&!userInfo.validate){
				$.confirm(["安全提示", validateHtml2, "取消", "确定"], false, function(box){
					validateConfirm(box, function(){
						$.go(0);
					});
					return false;
				});
			}else if(userInfo.isBind&&userInfo.validate){
				processAjax(checkCellCodeForBalancePayUrl, orderData, function(data){
					if(!data.flag)return false;
					$("#orderPayBalance").prop("disabled", true);
					$(_this).addClass("dis").off();
					updateSettleInfo(data);
				});
			}
		}
	});
	//获取验证码-未绑定
	$(document).on("click", "#getcode", function(){
		var _this = this;
		var cell = $("#validateCell").val()||'';
		var error = $("#validateError");
		if(!cell.match(cellReg)){
			error.text("手机号码格式有误");
			return false;
		}else{
			error.text("");
			$(_this).addClass("dis").html('<i></i>秒后重新获取');
			rTime($(_this).children("i").get(0), 59, function () {
				$(_this).text('再次发送').removeClass("dis");
			});
			getCellCode(cell);
			return false;
		}
	})
	//获取手机验证码-已绑定
	.on("click", "#getValidateCode", function(){
		var _this = this;
		$(_this).addClass("dis").html('<i></i>秒后重新获取');
		rTime($(_this).children("i").get(0), 59, function () {
			$(_this).text('再次发送').removeClass("dis");
		});
		processAjax(getCellCodeForBalancePayUrl, orderData);
	})
    //提交结算
    $("#orderSubmit").on("click", function () {
		if(orderData.member_address_id*1==0){
			$.tips("请选择地址");
			return false;
		}else if(!userInfo.isBind){
			$.confirm(["安全提示", validateHtml1, "取消", "确定"], false, function(box){
				validateConfirm(box);
				return false;
			});
		}else{
			userInfo.validate||delete orderData.member_money;
			$.loader("请稍候...");
			$.doAjax({
				url: settleOrderUrl,
				type: "post",
				data: orderData,
				success: function (data) {
					$.loaded();
					if(!data.flag){
						var coinMsg = data.msg.try_coin;//下单试豆错误字段名为try_coin
						if(coinMsg){//试豆不足//一个特例
							$.alert([coinMsg[0], "返回购物车"], function(){
								$.go(backUrl);
								return false;
							});
							return false;
						}
						for (var msg in data.msg) {
							if(isNaN(msg*1)){//非商品错误
								$.tips(data.msg[msg][0]);
							}else{//商品错误
								$.alert([data.msg[msg][0], "返回购物车"], function(){
									$.go(backUrl);
									return false;
								});
							}
							break;
						}
					}else{
						var url = data.payed ? settleSuccessPayedUrl : settleSuccessUrl;
						window.location.href = url + data.order_info_id;
					}
				}
			});
		}
		_hmt.push(['_trackEvent', '提交订单WAP', 'click', '提交订单WAP']);
    });
})

//获取手机验证码-未绑定
function getCellCode(cell, callback) {
	//callback({});return false;
    cell&&$.doAjax({
		url: getCellCodeUrl +  cell,
		success: function (data) {
			if (data.flag) {
				$.isFunction(callback) && callback(data)
			} else {
				$.tips(data.msg);
			}
		}
	});
}
//校验手机验证码-未绑定
function checkCellCode(cell, cellCode, callback) {
	//callback({});return false;
    $.doAjax({
		url: checkCellCodeUrl + cell + "&cellCode=" + cellCode,
		success: function (data) {
			if (data.flag) {
				$.isFunction(callback) && callback(data)
			} else {
				$.tips(data.msg)
			}
		}
	});
}
//短信验证弹框确定事件
function validateConfirm(box, callback){
	var cell = $("#validateCell").val()||'';
	var cellCode = $("#cellCode").val()||'';
	var error = $("#validateError");
	if(!cell.match(cellReg)){
		error.text("手机号码格式有误");
		return false;
	}else if(!cellCode.match(cellCodeReg)){
		error.text("验证码有误请重新输入！");
		return false;
	}else{
		checkCellCode(cell, cellCode, function(data){
			box.hide();
			userInfo.isBind = true;
			userInfo.validate = true;
			orderData.cell = cell;
			orderData.smsConfirm = cellCode;
			$.tips("手机绑定成功");
			$.isFunction(callback) && callback(data);
		});
	}
}
//处理请求事件
function processAjax(url, data, callback){
	$.loader("请稍候...");
	$.doAjax({
		url: url,
		type: "post",
		data: data,
		success: function (data) {
			$.loaded();
			$.isFunction(callback) && callback(data)
			if (!data.flag) {
				if(typeof data.msg == "string"){
					$.tips(data.msg)
				}else{
					for (var msg in data.msg) {
						$.tips(data.msg[msg][0]);
						break;
					}
				}
			}
		}
	});
}
//更新结算金额
function updateSettleInfo(data){
	$("#settleAmount").text(data.order_amount);
	$("#settleSD").text(data.try_coin);	//$("#settleExpressCharge").text(data.ship_amount_discount);//余额支付不要去跟新邮费金额，依然显示原始邮费
}